Binary search
Binary search is an algorithm technique based on the Divide and conquer paradigm. The most common example of binary search is to find an element in a sorted array in logarithmic time.
Description
Suppose you have an array of objects, and a predicate function , such that for each element , returns either or . Thus tests some property of the elements in
Furthermore, the array must satisfy the binary search property: there exists an index such that is for all , and is for all . When this holds, binary search can be used to find this index , i.e. the index of the leftmost element such that is true. The following pseudocode shows how.
int lo = 0,
hi = (int)A.size() - 1,
res = -1;
while (lo <= hi) {
int mid = (lo+hi)/2;
if (P(A[mid])) {
res = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
At completion, will be the index of the leftmost element such that is true (the index that we called above), or if no element in the array satisfies the property. Since the value of decreases by roughly half on every iteration, the algorithm takes time , where is the size of the input array
Applications
Say we want to find a specific element in a sorted array, or report that is not in the array. To do that, we define the property
Since the array is sorted, we can see that the binary search property is fulfilled: there is an index such that for all , is true, and for all , is false. Thus, using binary search we can find the index of the first element that satisfies the property in logarithmic time. If this element is equal to , then we're done, otherwise (and in the case that ) we can report that is not in the array.
It is also very common to use binary search when finding the minimum or maximum solution, even if there is no explicit array involved. Consider the problem The Monkey and the Oiled Bamboo. Notice that strength satisfies the binary search property: if we have a bigger strength factor than the minimum necessary, we will be able to reach the top, but if we have a smaller strength factor, then we won't be able to reach the top. Thus we can binary search , doing simulations of jumping to the top to evaluate the predicate for different values of
Variants
Binary search can also be applied over real numbers instead of integers. In that case the technique is known as the Bisection method

